import { createRouter, createWebHistory } from 'vue-router'
import { routes } from './routes'
import pinia from '@/store'
import useLoginStore from '@/store/login'
const router = createRouter({
    history: createWebHistory(),
    routes,
    scrollBehavior() {
        return { top: 0, left: 0 }
    },
})
// 不用进行token检查的白名单路径数组
const whiteList = ["/recommend", "/discovery/member",'/register'];
router.beforeEach(async (to, from, next) => {
    const loginStore = useLoginStore(pinia);
    const access_token_zww_2 = localStorage.getItem("ACCESS_TOKEN_ZWW_2");
    //记录要去的页面路由
    loginStore.toPath = to.path;
    //判断token是否存在
    if (access_token_zww_2) {
        const userInfo = loginStore.userInfo?.name;
        //判断用户信息是否存在
        if (userInfo) {
            next()
        } else {
            try {
                await loginStore.getUserInfo()
                next(to)
            } catch (error) {
                await loginStore.reset()
            }
        }
    } else {
        //登录  注册  资源  课程页 未登录时可以访问
        if (whiteList.indexOf(to.path) != -1) {
            next()
        } else {
            next(`/`)
        }
    }
})

export default router
